package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: getKthFromEnd
 * @author: chanzhugang
 * @create: 2022/10/27 00:56
 */
public class GetKthFromEnd {


    /**
     * 剑指offer 22 链表中倒数第k个节点
     * https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        // 快指针先走k步，然后慢指针从头开始走，直到快指针走完，此时慢指针就是倒数第k个节点
        ListNode fast = head;
        int count = 0;
        while (fast != null) {
            count++;
            if (count == k) {
                break;
            }
            fast = fast.next;
        }

        ListNode slow = head;
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    public ListNode getKthFromEnd2(ListNode head, int k) {
        // 快指针先走，k--， 直到k==0时，慢指针开始next
        ListNode fast = head;
        while (fast != null) {
            fast = fast.next;
            if (k == 0) {
                head = head.next;
            } else {
                k--;
            }
        }
        return head;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}